package org.eduapp.trains.dao.announce.impl;

import org.eduapp.trains.DAOException;
import org.eduapp.trains.dao.BaseDAOImpl;
import org.eduapp.trains.dao.announce.AnnounceDAO;
import org.eduapp.trains.model.announce.ModelAnnounce;
import org.eduapp.trains.utils.UtilsDateTime;
import org.eduapp.trains.utils.UtilsString;
import org.eduapp.trains.web.support.PaginationSupport;
import org.hibernate.Hibernate;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

public class AnnounceDAOImpl extends BaseDAOImpl<ModelAnnounce> implements AnnounceDAO {

	@Override
	public PaginationSupport<ModelAnnounce> get(ModelAnnounce model,
			int pageSize, int startIndex, String order, Boolean isDesc)
			throws DAOException {
		
		DetachedCriteria criteria = DetachedCriteria.forClass(ModelAnnounce.class);
		
		if (model != null) {
			criteria.add(Restrictions.ne("id", "1"));
			if (model.getAnnounceStatus() != null&&model.getAnnounceStatus()!=0) {
				criteria.add(Restrictions.eq("announceStatus", model.getAnnounceStatus()));
			}
			
			if (model.getAnnounceOwner() != null && 
					UtilsString.isNotEmpty(model.getAnnounceOwner().getId())) {
				criteria.createCriteria("announceOwner").add(
						Restrictions.eq("id", model.getAnnounceOwner().getId()));
			}
			
			if (UtilsString.isNotEmpty(model.getAnnounceSubject())) {
				criteria.add(Restrictions.ilike("announceSubject", model.getAnnounceSubject(), MatchMode.ANYWHERE));
			}
			
			if (model.getAnnounceCreateTime() != null) {
				criteria.add(Restrictions.sqlRestriction(
					"announce_create_time>=?", UtilsDateTime.dateString(model.getAnnounceCreateTime()) , Hibernate.STRING));
			}
			
		}
		
		if (UtilsString.isNotEmpty(order)) {
			if (isDesc != null && isDesc) {
				criteria.addOrder(Order.desc(order));
			} else {
				criteria.addOrder(Order.asc(order));
			}
		} else {
			criteria.addOrder(Order.desc("announceCreateTime"));
		}
		
		return findPageByCriteria(criteria, pageSize, startIndex);
	}

}
